package activity;

import android.app.Dialog;
import android.app.ProgressDialog;
import android.content.Intent;
import android.graphics.drawable.ColorDrawable;
import android.os.Bundle;
import android.os.Environment;
import android.os.Handler;
import android.os.Message;
import android.view.View;
import android.view.Window;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.TextView;

import com.laoxinwen.app.R;
import com.umeng.analytics.MobclickAgent;

import java.io.File;

import bean.OAuthInfo;
import bean.UserInfo;
import bean.wraper.DefaultIntWrapper;
import bean.wraper.DefaultStringWrapper;
import bean.wraper.UserInfoWrapper;
import common.HttpCallBack;
import common.Requester;
import common.UserConfig;
import share.LoginType;
import share.ShareActivity;
import util.DialogUtil;
import util.IntentUtil;
import util.ToastUtil;
import util.bitmap.FileUtil;
import util.bitmap.Img;
import util.bitmap.ImgUtil;

public class ProfileActivity extends ShareActivity {
    final private int REQUEST_CODE_SELECT_PIC_FROME_GALLERY = 2;
    final private int REQUEST_CODE_SELECT_PIC_FROME_CAMERA = 1;
    final private int REQUEST_CODE_CROP_PIC = 4;
    @id(R.id.iv_icon)
    private ImageView ivIcon;
    private String tmpFilePath;
    @id(R.id.tv_name)
    private TextView tvName;
    @id(R.id.tv_name_qq)
    private TextView tvNameQq;
    @id(R.id.tv_name_sina)
    private TextView tvNameSina;
    @id(R.id.tv_name_weixin)
    private TextView tvNameWeixin;
    private UserInfo user;
    @id(R.id.bt_bind_qq)
    private View vBindQq;
    @id(R.id.bt_bind_sina)
    private View vBindSina;
    @id(R.id.bt_bind_wechat)
    private View vBindWechat;

    @Override
    protected void onRightSlide() {
        finish();
    }

    @Override
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.bt_back:
                finish();
                break;
            case R.id.bt_edit:
                showDialogForEdit();
                break;
            case R.id.bt_camera:
                showDialog();
                break;
            case R.id.bt_bind_sina:
                if (userInfo.isSinaBinded) {
                    unBindSina();
                } else {
                    bindSina();
                }
                break;
            case R.id.bt_bind_wechat:
                if (userInfo.isWexinBinded) {
                    unBindWechat();
                } else {
                    bindWechat();
                }

                break;
            case R.id.bt_bind_qq:

                if (userInfo.isQqBinded) {
                    unBindQq();
                } else {
                    bindQq();
                }

                break;
            case R.id.bt_logout:
                logout();
                break;
        }
    }

    @Override
    public void onPause() {
        super.onPause();
        MobclickAgent.onPageEnd("个人信息页");
    }

    private void showDialogForEdit() {
        final Dialog dialog = new Dialog(this);
        dialog.setCancelable(true);
        dialog.getWindow().requestFeature(Window.FEATURE_NO_TITLE);
        dialog.setContentView(R.layout.dialog_password);
        dialog.getWindow().setBackgroundDrawable(new ColorDrawable(0));
        dialog.getWindow().findViewById(R.id.tv_ok).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                hideInputKeyboard();
                dialog.dismiss();
                final EditText et = (EditText) dialog.getWindow().findViewById(R.id.edit_text);
                String name = et.getText().toString().trim();
                if (name.equals("")) {
                    //TODO
                    ToastUtil.showShortToast("名字不能为空哦");
                }
                Requester.modifyName(name, new HttpCallBack<DefaultIntWrapper>() {
                    @Override
                    public void onSucceed(DefaultIntWrapper data) {
                        UserConfig.getUserInfo().setName(et.getText().toString());
                        UserConfig.updateUserInfo(UserConfig.getUserInfo());
                        tvName.setText(et.getText());
                    }
                });
            }
        });
        dialog.getWindow().findViewById(R.id.tv_cancel).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                dialog.dismiss();
            }
        });
        final EditText et = (EditText) dialog.getWindow().findViewById(R.id.edit_text);
        et.setText(tvName.getText());
        et.setSelection(tvName.getText().length());
        dialog.show();
    }

    public void showDialog() {
        final Dialog dialog = new Dialog(this);
        dialog.setCancelable(true);
        dialog.getWindow().requestFeature(Window.FEATURE_NO_TITLE);
        dialog.setContentView(R.layout.dialog_choose_pic);
        dialog.getWindow().setBackgroundDrawable(new ColorDrawable(0));
        dialog.getWindow().findViewById(R.id.from_gallery).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                dialog.dismiss();
                startActivityForResult(IntentUtil.getPicIntent(), REQUEST_CODE_SELECT_PIC_FROME_GALLERY);
            }
        });
        dialog.getWindow().findViewById(R.id.from_camera).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                dialog.dismiss();
                startActivityForResult(IntentUtil.getPicFromCameraIntent(tmpFilePath), REQUEST_CODE_SELECT_PIC_FROME_CAMERA);
            }
        });
        dialog.setCanceledOnTouchOutside(true);
        dialog.show();
    }

    private void logout() {
        DialogUtil.getConfirmDialog(this, "退出帐号", "确定要退出么，亲？", new DialogUtil.CallBack() {
            @Override
            public void onCallBack() {
                Requester.logout(new HttpCallBack<DefaultIntWrapper>() {
                    @Override
                    public void onSucceed(DefaultIntWrapper data) {
                        UserConfig.setIsLogin(false);
                        UserConfig.setLoginType(LoginType.NULL);
                        UserConfig.setRequestToken("");
                        UserConfig.clearSharedUserInfo();
                        finish();
                    }

                });
            }
        }).show();
    }

    @Override
    protected void onQqInfoObtained() {
        Requester.bind(LoginType.QQ, userInfo.qqOpenId, userInfo.qqName, userInfo.qqIconUrl, userInfo.qqToken, new HttpCallBack<DefaultIntWrapper>() {
            @Override
            public void onSucceed(DefaultIntWrapper data) {
                if (data.getData() == 1) {
                    userInfo.isQqBinded = true;
                    UserConfig.updateShareUserInfo(userInfo);
                    vBindQq.setSelected(userInfo.isQqBinded);
                    tvNameQq.setText(userInfo.qqName);
                } else {
                    showToast("绑定失败");
                }
            }
        });
    }

    @Override
    protected void onWeiboInfoObtained() {
        Requester.bind(LoginType.SINA, userInfo.sinaOpenId, userInfo.sinaName, userInfo.sinaIconUrl, userInfo.sinaToken, new HttpCallBack<DefaultIntWrapper>() {
            @Override
            public void onSucceed(DefaultIntWrapper data) {
                if (data.getData() == 1) {
                    userInfo.isSinaBinded = true;
                    UserConfig.updateShareUserInfo(userInfo);
                    vBindSina.setSelected(userInfo.isSinaBinded);
                    tvNameSina.setText(userInfo.sinaName);
                    showToast("绑定成功");
                } else {
                    showToast("绑定失败");
                }
            }

        });
    }

    @Override
    public void onResume() {
        super.onResume();
        MobclickAgent.onPageStart("个人信息页");
    }

    @Override
    protected void onWechatInfoObtain() {
        Requester.bind(LoginType.WECHAT, userInfo.weixinOpenId, userInfo.weixinName, userInfo.wexinIconUrl, userInfo.weixinToken, new HttpCallBack<DefaultIntWrapper>() {
            @Override
            public void onSucceed(DefaultIntWrapper data) {
                if (data.getData() == 1) {
                    userInfo.isWexinBinded = true;
                    UserConfig.updateShareUserInfo(userInfo);
                    vBindWechat.setSelected(userInfo.isWexinBinded);
                    tvNameWeixin.setText(userInfo.weixinName);
                } else {
                    showToast("绑定失败");
                }
            }
        });

    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_profile);
        loadView();
        initView();
        user = UserConfig.getUserInfo();
        Requester.getUserInfo(new HttpCallBack<UserInfoWrapper>() {
            @Override
            public void onSucceed(UserInfoWrapper data) {
                user = data.getData();
                UserConfig.updateUserInfo(data.getData());
                for (OAuthInfo o : user.getOauth()) {
                    if ("weixin".equals(o.getType())) {
                        userInfo.isWexinBinded = true;
                    } else if ("qq".equals(o.getType())) {
                        userInfo.isQqBinded = true;
                    } else if ("sinawb".equals(o.getType())) {
                        userInfo.isSinaBinded = true;
                    }
                }
                initView();
            }
        });
        tmpFilePath = Environment.getExternalStorageDirectory() + "/icontmp.jpg";
        new File(tmpFilePath).delete();
    }

    private void initView() {
        vBindQq.setSelected(userInfo.isQqBinded);
        vBindSina.setSelected(userInfo.isSinaBinded);
        vBindWechat.setSelected(userInfo.isWexinBinded);
        if (userInfo.isQqBinded) {
            tvNameQq.setText(userInfo.qqName);
        } else {
            tvNameQq.setText("未绑定");
        }
        if (userInfo.isSinaBinded) {
            tvNameSina.setText(userInfo.sinaName);
        } else {
            tvNameSina.setText("未绑定");
        }
        if (userInfo.isWexinBinded) {
            tvNameWeixin.setText(userInfo.weixinName);
        } else {
            tvNameWeixin.setText("未绑定");
        }
        tvName.setText(UserConfig.getUserInfo().getName());
        final Img img = new Img(FileUtil.getCacheDir(), FileUtil.getFileDir(), UserConfig.getUserInfo().getAvatar());
        img.setRadius(100);
        img.downloadAndDecodeAsync(new Handler() {
            @Override
            public void handleMessage(Message msg) {
                ivIcon.setImageBitmap(img.getBitmap());
            }
        });
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode == RESULT_OK) {
            switch (requestCode) {
                case REQUEST_CODE_SELECT_PIC_FROME_CAMERA:
                    startActivityForResult(IntentUtil.getCaptureIntent(new File(tmpFilePath), new File(tmpFilePath.replaceAll(".jpg", ".png"))), REQUEST_CODE_CROP_PIC);
                    break;
                case REQUEST_CODE_SELECT_PIC_FROME_GALLERY:
                    tmpFilePath = IntentUtil.getPicPath(this, data);
                    startActivityForResult(IntentUtil.getCaptureIntent(new File(tmpFilePath), new File(tmpFilePath.replaceAll(".jpg", ".png"))), REQUEST_CODE_CROP_PIC);
                    break;
                case REQUEST_CODE_CROP_PIC:
                    final ProgressDialog pd = new ProgressDialog(this);
                    File file = ImgUtil.compress(new File(tmpFilePath.replaceAll(".jpg", ".png")), 50, 40000);
                    Requester.modifyIcon(file, new HttpCallBack<DefaultStringWrapper>() {
                        @Override
                        public void onSucceed(DefaultStringWrapper data) {
                            UserConfig.getUserInfo().setAvatar(data.getData());
                            initView();
                            pd.cancel();
                        }

                        @Override
                        protected void onServerError(DefaultStringWrapper data) {
                            super.onServerError(data);
                            pd.cancel();
                        }

                        @Override
                        protected void onNetError() {
                            super.onNetError();
                            pd.cancel();
                        }
                    });
                    break;
            }
        }

    }

    @Override
    protected void unBindQq() {
        DialogUtil.getConfirmDialog(this, "解除绑定", "确定要解除QQ绑定么，亲？", new DialogUtil.CallBack() {
            @Override
            public void onCallBack() {
                Requester.unbind(LoginType.QQ, new HttpCallBack<DefaultIntWrapper>() {
                    @Override
                    public void onSucceed(DefaultIntWrapper data) {
                        if (data.getData() == 1) {
                            userInfo.isQqBinded = false;
                            UserConfig.updateShareUserInfo(userInfo);
                            ProfileActivity.super.unBindQq();
                            vBindQq.setSelected(false);
                            tvNameQq.setText("未绑定");
                        } else {
                            showToast("解绑QQ失败");
                        }
                    }
                });

            }
        }).show();

    }

    protected void unBindSina() {
        DialogUtil.getConfirmDialog(this, "解除绑定", "确定要解除新浪绑定么，亲？", new DialogUtil.CallBack() {
            @Override
            public void onCallBack() {
                Requester.unbind(LoginType.SINA, new HttpCallBack<DefaultIntWrapper>() {
                    @Override
                    public void onSucceed(DefaultIntWrapper data) {
                        if (data.getData() == 1) {
                            userInfo.isSinaBinded = false;
                            UserConfig.updateShareUserInfo(userInfo);
                            ProfileActivity.super.unBindSina();
                            vBindSina.setSelected(false);
                            tvNameSina.setText("未绑定");
                        } else {
                            showToast("解绑新浪失败");
                        }
                    }
                });
            }
        }).show();

    }

    protected void unBindWechat() {
        DialogUtil.getConfirmDialog(this, "解除绑定", "确定要解除微信绑定么，亲？", new DialogUtil.CallBack() {
            @Override
            public void onCallBack() {
                Requester.unbind(LoginType.WECHAT, new HttpCallBack<DefaultIntWrapper>() {
                    @Override
                    public void onSucceed(DefaultIntWrapper data) {
                        if (data.getData() == 1) {

                            userInfo.isWexinBinded = false;
                            UserConfig.updateShareUserInfo(userInfo);
                            ProfileActivity.super.unBindWechat();
                            vBindWechat.setSelected(false);
                            tvNameWeixin.setText("未绑定");
                        } else {
                            showToast("解绑QQ失败");
                        }
                    }
                });

            }
        }).show();
    }
}
